<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" class="!w-240px" clearable placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PROPERTY_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          v-hasPermi="['product:property:create']"
          plain
          type="primary"
          @click="openForm('create')"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
        <el-button
          plain
          type="success"
          @click="openGenerateSku"
        >
          <Icon class="mr-5px" icon="ep:tickets" />
          生成库存
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column align="center" label="编号" min-width="60" prop="id" />
      <el-table-column align="center" label="上级" prop="parentId" min-width="100" :formatter="parentFormatter" />
      <el-table-column align="center" label="属性名称" prop="name" min-width="150" />
      <el-table-column align="center" label="状态" prop="status" min-width="80">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PROPERTY_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" align="center" label="备注" prop="remark" />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="createTime"
        width="180"
      />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button link type="primary" @click="openDetail(scope.row)">查看</el-button>
          <el-button
            v-hasPermi="['product:property:update']"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button link type="primary" @click="goValueList(scope.row.id)">属性值</el-button>
          <el-button
            v-hasPermi="['product:property:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PropertyForm ref="formRef" @success="getList" />

  <!-- 详情弹窗 -->
  <Dialog v-model="detailVisible" title="属性详情" width="600px">
    <el-descriptions :column="1" border>
      <el-descriptions-item label="编号">{{ detailData.id }}</el-descriptions-item>
      <el-descriptions-item label="属性名称">{{ detailData.name }}</el-descriptions-item>
      <el-descriptions-item label="上级">
        {{ getParentName(detailData.parentId) }}
      </el-descriptions-item>
      <el-descriptions-item label="状态">
        <dict-tag :type="DICT_TYPE.PROPERTY_STATUS" :value="detailData.status" />
      </el-descriptions-item>
      <el-descriptions-item label="备注">{{ detailData.remark || '-' }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ formatDate(detailData.createTime) }}
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="detailVisible = false">关 闭</el-button>
    </template>
  </Dialog>

  <!-- 生成库存弹窗 -->
  <Dialog v-model="skuGenerateVisible" title="生成SKU库存" width="900px">
    <el-form label-width="100px">
      <el-form-item label="SPU商品">
        <el-input
          v-model="selectedSpuName"
          readonly
          class="!w-400px"
          placeholder="加载中..."
        />
        <el-button type="primary" :loading="generating" @click="generateSkus" class="ml-10px">
          <Icon class="mr-5px" icon="ep:magic-stick" />
          生成SKU
        </el-button>
      </el-form-item>
    </el-form>

    <el-divider />

    <div v-if="generatedSkus.length > 0">
      <el-alert title="生成结果" type="success" :closable="false" class="mb-10px">
        共生成 {{ generatedSkus.length }} 个SKU组合
      </el-alert>
      <el-table :data="generatedSkus" border max-height="400">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="规格组合" min-width="300">
          <template #default="{ row }">
            <el-tag
              v-for="(prop, index) in row.properties"
              :key="index"
              class="mr-5px"
              size="small"
            >
              {{ prop.propertyName }}: {{ prop.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="120" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.price"
              :min="0"
              :precision="2"
              :controls="false"
              class="!w-100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="库存" width="100" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.stock"
              :min="0"
              :controls="false"
              class="!w-80px"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <el-button @click="skuGenerateVisible = false">取 消</el-button>
      <el-button
        type="primary"
        :loading="saving"
        :disabled="generatedSkus.length === 0"
        @click="saveSkus"
      >
        保存SKU
      </el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as PropertyApi from '@/api/mall/product/property'
import * as SpuApi from '@/api/mall/product/spu'
import PropertyForm from './PropertyForm.vue'

const { push } = useRouter()

defineOptions({ name: 'ProductProperty' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  status: undefined,
  type: 1,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

// 详情相关
const detailVisible = ref(false) // 详情弹窗是否显示
const detailData = ref<any>({}) // 详情数据

// 生成SKU相关
const skuGenerateVisible = ref(false) // 生成SKU弹窗是否显示
const selectedSpuId = ref<number>() // 选中的SPU ID
const selectedSpuName = ref<string>('') // 选中的SPU名称
const generatedSkus = ref<any[]>([]) // 生成的SKU列表
const generating = ref(false) // 正在生成中
const saving = ref(false) // 正在保存中
const allProperties = ref<PropertyApi.PropertyVO[]>([]) // 所有属性
const allPropertyValues = ref<Map<number, PropertyApi.PropertyValueVO[]>>(new Map()) // 所有属性值，key为propertyId

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PropertyApi.getPropertyPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 上级名称格式化 */
const parentFormatter = (row: any) => {
  if (!row.parentId || row.parentId === 0) return '-'
  const parent = list.value.find((item: any) => item.id === row.parentId)
  return parent ? parent.name : row.parentId
}

/** 获取上级名称 */
const getParentName = (parentId: number) => {
  if (!parentId || parentId === 0) return '一级层级'
  const parent = list.value.find((item: any) => item.id === parentId)
  return parent ? parent.name : parentId
}

/** 打开详情 */
const openDetail = (row: any) => {
  detailData.value = row
  detailVisible.value = true
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PropertyApi.deleteProperty(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 跳转商品属性列表 */
const goValueList = (id: number) => {
  push({ name: 'ProductPropertyValue', params: { propertyId: id } })
}

/** 打开生成SKU弹窗 */
const openGenerateSku = async () => {
  skuGenerateVisible.value = true
  generatedSkus.value = []
  selectedSpuId.value = undefined
  selectedSpuName.value = '加载中...'
  
  try {
    // 查询 spuType=1 的SPU（配送卡类型）
    const spuData: any = await SpuApi.getSpuPage({ pageNo: 1, pageSize: 100, spuType: 1 } as any)
    const spuList = spuData.list || []
    
    if (spuList.length === 0) {
      message.warning('未找到配送卡类型的SPU（spuType=1）')
      selectedSpuName.value = '未找到配送卡SPU'
      return
    }
    
    // 自动填充第一条（应该只有一条）
    const targetSpu = spuList[0]
    selectedSpuId.value = targetSpu.id
    selectedSpuName.value = targetSpu.name
    
    if (spuList.length > 1) {
      message.info(`找到 ${spuList.length} 条配送卡SPU，已自动选择第一条`)
    }
    
    // 加载所有属性（type=1的配送卡属性）
    const propData: any = await PropertyApi.getPropertyPage({ pageNo: 1, pageSize: 1000, type: 1 } as any)
    allProperties.value = propData.list || []
    
    // 加载所有属性值
    for (const prop of allProperties.value) {
      if (prop.id) {
        const values = await PropertyApi.getPropertyValueSimpleList(prop.id)
        allPropertyValues.value.set(prop.id, values)
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
    selectedSpuName.value = '加载失败'
  }
}

/** 生成SKU组合 */
const generateSkus = async () => {
  if (!selectedSpuId.value) {
    message.warning('请先选择SPU')
    return
  }
  
  generating.value = true
  try {
    // 1. 获取一级属性（类型，parentId=0）
    const level1Properties = allProperties.value.filter(p => p.parentId === 0)
    
    if (level1Properties.length === 0) {
      message.warning('没有找到一级属性（类型）')
      return
    }
    
    const skuCombinations: any[] = []
    
    // 2. 遍历每个一级属性的每个属性值（如：电子卡、实体卡）
    for (const level1Prop of level1Properties) {
      const level1Values = allPropertyValues.value.get(level1Prop.id!) || []
      
      for (const level1Value of level1Values) {
        // 3. 获取该一级属性值下的二级属性（如：期限、次卡）
        const level2Properties = allProperties.value.filter(p => p.parentId === level1Prop.id)
        
        for (const level2Prop of level2Properties) {
          const level2Values = allPropertyValues.value.get(level2Prop.id!) || []
          
          for (const level2Value of level2Values) {
            // 4. 获取该二级属性值下的三级属性（如：版本）
            const level3Properties = allProperties.value.filter(p => p.parentId === level2Prop.id)
            
            for (const level3Prop of level3Properties) {
              const level3Values = allPropertyValues.value.get(level3Prop.id!) || []
              
              for (const level3Value of level3Values) {
                // 生成一个完整的3层SKU组合
                skuCombinations.push({
                  spuId: selectedSpuId.value,
                  properties: [
                    {
                      propertyId: level1Prop.id,
                      propertyName: level1Prop.name,
                      valueId: level1Value.id,
                      valueName: level1Value.name
                    },
                    {
                      propertyId: level2Prop.id,
                      propertyName: level2Prop.name,
                      valueId: level2Value.id,
                      valueName: level2Value.name
                    },
                    {
                      propertyId: level3Prop.id,
                      propertyName: level3Prop.name,
                      valueId: level3Value.id,
                      valueName: level3Value.name
                    }
                  ],
                  price: 0,
                  marketPrice: 0,
                  costPrice: 0,
                  stock: 0,
                  picUrl: ''
                })
              }
            }
          }
        }
      }
    }
    
    generatedSkus.value = skuCombinations
    
    if (skuCombinations.length === 0) {
      message.warning('没有生成任何SKU组合，请检查属性配置是否完整（需要3层结构）')
    } else {
      message.success(`成功生成 ${skuCombinations.length} 个SKU组合`)
    }
  } catch (error) {
    console.error('生成SKU失败:', error)
    message.error('生成SKU失败')
  } finally {
    generating.value = false
  }
}

/** 保存SKU到数据库 */
const saveSkus = async () => {
  if (generatedSkus.value.length === 0) {
    message.warning('没有可保存的SKU')
    return
  }
  
  saving.value = true
  try {
    // 获取当前SPU详情
    const spu = await SpuApi.getSpu(selectedSpuId.value!)
    
    // 将生成的SKU添加到SPU的skus数组中
    const updatedSpu = {
      ...spu,
      skus: [
        ...(spu.skus || []),
        ...generatedSkus.value
      ]
    }
    
    // 更新SPU（包含SKU数据）
    await SpuApi.updateSpu(updatedSpu)
    
    message.success('SKU保存成功')
    skuGenerateVisible.value = false
  } catch (error) {
    console.error('保存SKU失败:', error)
    message.error('保存SKU失败')
  } finally {
    saving.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
